package com.MetaverseMaker.UniverseFarm.controller;

/**
 * @Auther: wanghuiqian
 * @Date: 2021/11/23 - 11 - 23 - 21:06
 * @Description: controller
 * @version: 1.0
 */

import com.MetaverseMaker.UniverseFarm.dto.MyMessage;
import com.MetaverseMaker.UniverseFarm.dto.MySoilForPage;
import com.MetaverseMaker.UniverseFarm.dto.SoilNum;
import com.MetaverseMaker.UniverseFarm.entity.SoilInfo;
import com.MetaverseMaker.UniverseFarm.entity.SoilInfoExample;
import com.MetaverseMaker.UniverseFarm.entity.UserInfo;
import com.MetaverseMaker.UniverseFarm.service.IUserInfoService;
import com.MetaverseMaker.UniverseFarm.service.impl.CartInfoServiceImpl;
import com.MetaverseMaker.UniverseFarm.service.impl.OrderInfoServiceImpl;
import com.MetaverseMaker.UniverseFarm.service.impl.SoilInfoServiceImpl;
import javassist.expr.NewArray;
import org.apache.catalina.Session;
import org.apache.catalina.realm.UserDatabaseRealm;
import org.apache.commons.io.FileUtils;
import org.aspectj.bridge.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.*;


@Controller
public class SoilController {
    @Autowired
    private SoilInfoServiceImpl soilInfoService;
    @Autowired
    private IUserInfoService iUserInfoService;
    @Autowired
    private CartInfoServiceImpl cartInfoService;
    @Autowired
    private OrderInfoServiceImpl orderInfoService;
//
//    public GoodsService getGoodsService() {
//        return goodsService;
//    }
//
//    @Autowired
//    public void setGoodsService(GoodsService goodsService) {
//        this.goodsService = goodsService;
//    }
//
    @RequestMapping("/showSoil")
    @ResponseBody
    public MyMessage showsoil(){
        List<SoilInfo> list = soilInfoService.findAll();
        MyMessage myMessage=new MyMessage();
        if (list==null)
        {
            myMessage.setFlag(0);
        }
        else
        {
            myMessage.setFlag(1);
            myMessage.setData(list);
        }
        return myMessage;
    }
    @RequestMapping("/getSoilByTypeAndLimit")
    @ResponseBody
    public MyMessage  getSoilByTypeAndLimit(String type,Integer limit){
        MyMessage my=new MyMessage();
        List<SoilInfo> list= soilInfoService.querysoilByTypeAndLimit(type,limit);
        if(list==null||list.size()==0){
            my.setFlag(0);
        }else{
            my.setFlag(1);
            my.setData(list);
        }
        return my;
    }

    /**
     * 分页的控制器
     * @param page  当前页数
     * @param size  每页显示条数
     * @return    消息对象   封装了返回的MyGoodsForPage的数据
     */
    @RequestMapping("/getGoodsByPage")
    @ResponseBody
    public MyMessage getGoodsByPage(String page,String size) throws Exception {
        int realpage=1;
        int realsize=9;
        //容错
        if(page==null||size==null){
            realpage=1;
            realsize=9;
        }
        //如果传入的非数字的内容
        try{
            realpage=Integer.valueOf(page);
        }catch (Exception e){
            realpage=1;
        }
        try{
            realsize=Integer.valueOf(size);
        }catch (Exception e){
            realsize=9;
        }
        //对负数容错
        if(realpage<=0){
            realpage=1;
        }
        if(realsize<=0){
            realsize=9;
        }
        //总页数=总条数/每页显示条数
        /**
         *    总页数   pageCount
         *    总条数   count
         *    每页显示条数   realsize
         *    pageCount=(count/realsize==0)?(count/realsize):(count/realsize+1);
         */
        //获取总条数
//        List<SoilInfo> list=soilInfoService.findAll();
//        int count=list.size();
        int count=soilInfoService.getsoilCount().getMycount();
        //获取总页数

        int pageCount=(count%realsize==0)?(count/realsize):(count/realsize+1);

        //对页数上限容错
        realpage=realpage>pageCount?pageCount:realpage;

        //根据有效的当前页数和每页显示条数获取对应页的数据
        System.out.println((realpage-1)*realsize);
        System.out.println(realsize);
        List<SoilInfo> list= soilInfoService.querysoilForPage((realpage-1)*realsize,realsize);
        List<SoilInfo> list1=new ArrayList<>();
        List<UserInfo> list2=new ArrayList<>();
        for(SoilInfo soilInfo:list)
        {
            if(!soilInfo.getSoilFruit().contains("农场"))
            {
                list1.add(soilInfo);
                list2.add(iUserInfoService.findUserById(soilInfo.getSoilUserid()));
            }
        }
        System.out.println(list1);
        MySoilForPage mgfp=new MySoilForPage();
        mgfp.setPage(realpage);
        mgfp.setPagedata(list1);
        mgfp.setSize(realsize);
        mgfp.setPageCount(pageCount);

        MyMessage my=new MyMessage();
        my.setUsermsg(list2);
        if(list.size()==0){
            my.setFlag(0);
        }else{
            my.setFlag(1);
            my.setData(mgfp);
        }
        System.out.println("products");
        return my;
    }
    //分页查找所有土地
    @RequestMapping("/getSoilsByPage")
    @ResponseBody
    public MyMessage getSoilsByPage(String page,String size) throws Exception {
        int realpage=1;
        int realsize=9;
        //容错
        if(page==null||size==null){
            realpage=1;
            realsize=9;
        }
        //如果传入的非数字的内容
        try{
            realpage=Integer.valueOf(page);
        }catch (Exception e){
            realpage=1;
        }
        try{
            realsize=Integer.valueOf(size);
        }catch (Exception e){
            realsize=9;
        }
        //对负数容错
        if(realpage<=0){
            realpage=1;
        }
        if(realsize<=0){
            realsize=9;
        }
        //总页数=总条数/每页显示条数
        /**
         *    总页数   pageCount
         *    总条数   count
         *    每页显示条数   realsize
         *    pageCount=(count/realsize==0)?(count/realsize):(count/realsize+1);
         */
        //获取总条数
//        List<SoilInfo> list=soilInfoService.findAll();
//        int count=list.size();
        int count=soilInfoService.getsoilCount().getMycount();
        //获取总页数

        int pageCount=(count%realsize==0)?(count/realsize):(count/realsize+1);

        //对页数上限容错
        realpage=realpage>pageCount?pageCount:realpage;

        //根据有效的当前页数和每页显示条数获取对应页的数据
        System.out.println((realpage-1)*realsize);
        System.out.println(realsize);
        List<SoilInfo> list= soilInfoService.querysoilForPage((realpage-1)*realsize,realsize);
        List<SoilInfo> list1=new ArrayList<>();
        List<UserInfo> list2=new ArrayList<>();
        for(SoilInfo soilInfo:list)
        {
            if(soilInfo.getSoilFruit().contains("农场"))
            {
                System.out.println(list1);
                list1.add(soilInfo);
                list2.add(iUserInfoService.findUserById(soilInfo.getSoilUserid()));
            }
        }

        MySoilForPage mgfp=new MySoilForPage();
        mgfp.setPage(realpage);
        mgfp.setPagedata(list1);
        mgfp.setSize(realsize);
        mgfp.setPageCount(pageCount);

        MyMessage my=new MyMessage();
        if(list.size()==0){
            my.setFlag(0);
        }else{
            my.setFlag(1);
            my.setData(mgfp);
            my.setUsermsg(list2);
        }
        System.out.println("soils");
        return my;
    }


    //查找单个产品，用于产品详情界面
    @RequestMapping("/getSoilGoodById")
    @ResponseBody
    public MyMessage getSoilGoodById(Integer soilid, HttpSession session){
        MyMessage my=new MyMessage();
        System.out.println("soilId="+soilid);
        SoilInfo soilInfo=  soilInfoService.querySoilGoodById(soilid);
        if(soilInfo!=null){
            System.out.println("soilInfo1="+soilInfo);
            my.setFlag(1);
            my.setData(soilInfo);
        }else{
            System.out.println("soilInfo2="+soilInfo);
            my.setFlag(0);
        }
        return my;
    }
    //查找单个农场，用于农场详情界面
    @RequestMapping("/getSoilById")
    @ResponseBody
    public MyMessage getSoilById(Integer soilid, HttpSession session) throws Exception {
        MyMessage my=new MyMessage();
        System.out.println("soilId="+soilid);
        SoilInfo soilInfo=  soilInfoService.findSoilInfoById(soilid);
        if(soilInfo!=null){
            System.out.println("soilInfo1="+soilInfo);
            my.setFlag(1);
            my.setData(soilInfo);
        }else{
            System.out.println("soilInfo2="+soilInfo);
            my.setFlag(0);
        }
        return my;
    }
    //根据当前登录用户id查找已经拥有的产品，仅用于用户个人信息界面
    @RequestMapping("/getSoilGoodsByUserId")
    @ResponseBody
    public MyMessage getSoilGoodsByUserId(HttpSession session){
        MyMessage my=new MyMessage();
        UserInfo userInfo= (UserInfo) session.getAttribute("loginuser");
        List<SoilInfo> list= soilInfoService.findSoilGoodsInfoByUserId(userInfo);
        if(list!=null){
            my.setFlag(1);
            my.setData(list);
        }else{
            my.setFlag(0);
        }
        return my;
    }
    //根据当前登录用户id查找已经拥有的土地们
    @RequestMapping("/getSoilByUserId")
    @ResponseBody
    public MyMessage getSoilByUserId(HttpSession session){
        MyMessage my=new MyMessage();
        UserInfo userInfo= (UserInfo) session.getAttribute("loginuser");
        List<SoilInfo> list= soilInfoService.findSoilInfoByUserId(userInfo);
        if(list!=null){
            my.setFlag(1);
            my.setData(list);
        }else{
            my.setFlag(0);
        }
        return my;
    }

    //根据当前登录用户id分页查找拥有的土地
    @RequestMapping("/getSoilsByPageAndUserID")
    @ResponseBody
    public MyMessage getSoilsByPageAndUserID(String page,String size,HttpSession session) throws Exception {
        int realpage=1;
        int realsize=9;
        //容错
        if(page==null||size==null){
            realpage=1;
            realsize=9;
        }
        //如果传入的非数字的内容
        try{
            realpage=Integer.valueOf(page);
        }catch (Exception e){
            realpage=1;
        }
        try{
            realsize=Integer.valueOf(size);
        }catch (Exception e){
            realsize=9;
        }
        //对负数容错
        if(realpage<=0){
            realpage=1;
        }
        if(realsize<=0){
            realsize=9;
        }
        //总页数=总条数/每页显示条数
        /**
         *    总页数   pageCount
         *    总条数   count
         *    每页显示条数   realsize
         *    pageCount=(count/realsize==0)?(count/realsize):(count/realsize+1);
         */
        //获取总条数
//        List<SoilInfo> list=soilInfoService.findAll();
//        int count=list.size();
        int count=soilInfoService.getsoilCount().getMycount();
        //获取总页数

        int pageCount=(count%realsize==0)?(count/realsize):(count/realsize+1);

        //对页数上限容错
        realpage=realpage>pageCount?pageCount:realpage;

        //根据有效的当前页数和每页显示条数获取对应页的数据
        System.out.println((realpage-1)*realsize);
        System.out.println(realsize);
        List<SoilInfo> list= soilInfoService.querysoilForPage((realpage-1)*realsize,realsize);
        List<SoilInfo> list1=new ArrayList<>();
        List<UserInfo> list2=new ArrayList<>();
        UserInfo userInfo= (UserInfo) session.getAttribute("loginuser");
        for(SoilInfo soilInfo:list)
        {
            if(soilInfo.getSoilFruit().contains("农场")&&soilInfo.getSoilUserid()==userInfo.getUserId())
            {
                System.out.println(list1);
                list1.add(soilInfo);
                list2.add(iUserInfoService.findUserById(soilInfo.getSoilUserid()));
            }
        }

        MySoilForPage mgfp=new MySoilForPage();
        mgfp.setPage(realpage);
        mgfp.setPagedata(list1);
        mgfp.setSize(realsize);
        mgfp.setPageCount(pageCount);

        MyMessage my=new MyMessage();
        if(list.size()==0){
            my.setFlag(0);
        }else{
            my.setFlag(1);
            my.setData(mgfp);
            my.setUsermsg(list2);
        }
        System.out.println("soils");
        return my;
    }
    @RequestMapping("/getSoilTypeNumber")
    @ResponseBody
    public MyMessage  getSoilTypeNumber(){
        MyMessage my=new MyMessage();
        List<SoilNum> list=  soilInfoService.querysoilTypeNum();
        if(list==null||list.size()==0){
            my.setFlag(0);
        }else{
            my.setFlag(1);
            my.setData(list);
        }
        return my;
    }
    @RequestMapping("/getSixSoil")
    @ResponseBody
    public MyMessage getFourSoil() throws Exception {
        MyMessage message=new MyMessage();
        System.out.println(111);
        List<SoilInfo> list=soilInfoService.findAll();
        if(list==null||list.size()==0){
            message.setFlag(0);
        }
        else {
            Collections.sort(list, new Comparator<SoilInfo>() {
                @Override
                public int compare(SoilInfo o1, SoilInfo o2) {
                    return Integer.parseInt(o1.getSoilPrice()) - Integer.parseInt(o2.getSoilPrice());
                }
            });
            message.setFlag(1);
            List<SoilInfo> list1= new ArrayList<>();
            List<UserInfo> list2=new ArrayList<>();
            int cnt=0;
            int num=0;
            while(true)
            {
                if(num==6)
                    break;
                if(!(list.get(cnt).getSoilFruit().contains("农场")))
                {
                    list1.add(list.get(cnt));
                    UserInfo userInfo= iUserInfoService.findUserById(list.get(cnt).getSoilUserid());
                    list2.add(userInfo);
                    num++;
                }
                cnt++;
            }
            message.setData(list1);
            message.setUsermsg(list2);
            System.out.println(list1);
        }
        return message;
    }
    @RequestMapping("/irrigate")
    @ResponseBody
    public MyMessage irrigaet(int soilid,HttpSession session) throws Exception {
        MyMessage message=new MyMessage();
        SoilInfo soilInfo=soilInfoService.findSoilInfoById(soilid);
        boolean f1=true;
        if(soilInfo.getSoilStatus()==1)
            f1=false;
        if(f1)
        {
            System.out.println(soilInfo);
            soilInfo.setSoilStatus(1);
            soilInfo.setSoilMaturity(soilInfo.getSoilMaturity()+8);
            boolean f=soilInfoService.update(soilInfo);
            message.setFlag(1);
            message.setMsg("灌溉成功!!!");
            message.setData(soilInfo.getSoilMaturity());
        }
        else
        {
            message.setFlag(0);
            message.setMsg("亲，您今天已经浇过水了!!!");
        }
        return message;
    }
    @RequestMapping("/getSoils")
    @ResponseBody
    public MyMessage getSoils(HttpSession session) throws Exception {
        MyMessage message=new MyMessage();
        List<SoilInfo> list=soilInfoService.findAll();
        Collections.sort(list, new Comparator<SoilInfo>() {
            @Override
            public int compare(SoilInfo o1, SoilInfo o2) {
                return o2.getSoilMaturity()-o1.getSoilMaturity();
            }
        });
        int cnt=0;
        List<SoilInfo> list1=new ArrayList<>();
        List<UserInfo> list2=new ArrayList<>();
        for(SoilInfo soilInfo:list)
        {
            if(cnt==6)
                break;
            if(soilInfo.getSoilFruit().contains("农场"))
            {
                cnt++;
                list1.add(soilInfo);
                UserInfo userInfo= iUserInfoService.findUserById(list.get(cnt).getSoilUserid());
                list2.add(userInfo);
            }
        }
        message.setData(list1);
        message.setUsermsg(list2);
        message.setFlag(1);
        return message;
    }
    @RequestMapping("/harvest")
    @ResponseBody
    public MyMessage harvest(int soilid,String addGoodName,String addGoodDes,
        String addGoodPrice,String addGoodPhoto,int addGoodStatus,int addGoodMaturity,
        String addGoodFruit,HttpSession session) throws Exception {
        MyMessage message=new MyMessage();
        SoilInfo soilInfo=soilInfoService.findSoilInfoById(soilid);
        System.out.println(soilInfo);
        //soilInfo.setSoilStatus(1);
        int boxes=soilInfo.getSoilMaturity()/10;
        if(boxes>0){
            soilInfo.setSoilMaturity(soilInfo.getSoilMaturity()%10);
            boolean f=soilInfoService.update(soilInfo);
            if(f)
            {
                UserInfo userInfo= (UserInfo) session.getAttribute("loginuser");

                SoilInfo addSoilInfo=new SoilInfo();
                addSoilInfo.setSoilName(addGoodName);
                addSoilInfo.setSoilDes(addGoodDes);
                addSoilInfo.setSoilPrice(addGoodPrice);
                addSoilInfo.setSoilPhoto(addGoodPhoto);
                addSoilInfo.setSoilStatus(addGoodStatus);
                addSoilInfo.setSoilMaturity(addGoodMaturity);
                addSoilInfo.setSoilFruit(addGoodFruit);
                addSoilInfo.setSoilUserid(userInfo.getUserId());
                //修改了insert，使得可以返回自增id
                boolean g=soilInfoService.save(addSoilInfo);
                if(g){
                    message.setUsermsg(boxes);
                    message.setFlag(1);
                    message.setMsg("收获&发布成功!!!");
                    //把新生成的产品转发回去用于生成照片
                    message.setData(addSoilInfo);
                    System.out.println("addSoilInfo="+addSoilInfo);
                }else{
                    message.setFlag(0);
                    message.setMsg("发布失败!!!");
                }
            }
            else
            {
                message.setFlag(0);
                message.setMsg("收获失败!!!");
            }
        }else {
            message.setFlag(0);
            message.setMsg("收获失败!!!成熟度不足10！");
        }

        return message;
    }
    @RequestMapping("/uploadGoodImg")
    @ResponseBody
    public MyMessage  uploadGoodImg(@RequestParam MultipartFile file,Integer goodId, HttpServletRequest request, HttpSession session) throws Exception {
        //MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;

        //int goodId=mRequest.getFile("goodId");

        System.out.println("goodId="+goodId);
        System.out.println(session.getId());
        //获取上传图片的原名称
        String fileName=file.getOriginalFilename();
        System.out.println(fileName);
        //获取要保存的目录
        String path =request.getServletContext().getRealPath("static/picture/goods");
        System.out.println(path);
        //上传的文件最好是要重命名，这样才能保存不会因为上传相同名称的文件而报错
        fileName=System.currentTimeMillis()+"_"+fileName;
        System.out.println(fileName);
        //构造file对象
        File myfile=new File(path+"/"+fileName);
        boolean flag=false;
        try {
            //将前段的文件复制到后端服务器中
            FileUtils.copyInputStreamToFile(file.getInputStream(),myfile);
            flag=true;
            System.out.println("上传成功");
            //上传成功后还需要更新数据库中的用户logo
            //UserInfo user= (UserInfo) session.getAttribute("loginuser");
            SoilInfo goodInfo=soilInfoService.querySoilGoodById(goodId);
            goodInfo.setSoilPhoto(fileName);
            boolean flag2=soilInfoService.update(goodInfo);
            if(flag2){
//                user.setUser_logo(fileName);
                System.out.println("上传商品图片成功！");
            }
        }catch (Exception e){
        }
        MyMessage my=new MyMessage();
        if(flag){
            //上传成功
            my.setFlag(1);
            /*my.setData(fileName);*/

            /*UserInfo user2= (UserInfo) session.getAttribute("loginuser");
            UserInfo user3=iUserInfoService.findUserById(user2.getUserId());
            session.setAttribute("loginuser",user3);*/
            SoilInfo goodInfo2=soilInfoService.querySoilGoodById(goodId);
            session.setAttribute("goodInfo",goodInfo2);
        }else{
            //上传失败
            my.setFlag(0);
        }
        return my;
    }
    /**
     * 偷取能量
     */
    @RequestMapping("/steal")
    @ResponseBody
    public MyMessage steal(int soilId,HttpSession session) throws Exception {
        UserInfo userInfo=(UserInfo) session.getAttribute("loginuser");
        MyMessage message=new MyMessage();
        SoilInfo soilInfo=soilInfoService.findSoilInfoById(soilId);
        if(userInfo==null)
        {
            message.setFlag(2);
            message.setMsg("请登录!!!");
            return message;
        }
        else {
            if (soilInfo.getSoilStatus() == 1) {
                message.setFlag(0);
                message.setMsg("以加保护罩或已被偷取!!!");
                return message;
            } else {
                soilInfo.setSoilStatus(1);
                soilInfo.setSoilMaturity(soilInfo.getSoilMaturity() - 5);
                soilInfoService.update(soilInfo);
                List<SoilInfo> list=soilInfoService.findSoilInfoByUserId(userInfo);
                if(list.size()==0)
                {
                    message.setFlag(3);
                    message.setMsg("你还没有土地，能量流失了!!!");
                    return message;
                }
                else {
                    int size = list.size();
                    Random random = new Random();
                    int ran = random.nextInt(size);
                    System.out.println(ran);
                    list.get(ran).setSoilMaturity(list.get(ran).getSoilMaturity() + 5);
                    soilInfoService.update(list.get(ran));
                    message.setFlag(1);
                    message.setMsg("恭喜你是第一个来偷取的,且主人在睡懒觉，偷取成功!!!");
                    message.setData(list.get(ran));
                    return message;
                }
            }
        }
    }
    @RequestMapping("/send")
    @ResponseBody
    public MyMessage send(String account,String pwd,int soilid, HttpSession session) throws Exception {
        MyMessage message=new MyMessage();
        SoilInfo soilInfo=soilInfoService.findSoilInfoById(soilid);
        cartInfoService.addItem(soilInfo);
        soilInfo.setSoilUserid(0);
        soilInfoService.update(soilInfo);
        System.out.println(account);
        System.out.println(pwd);
        UserInfo userInfo=(UserInfo)session.getAttribute("loginuser");
        if(userInfo==null)
        {
            message.setFlag(0);
            message.setMsg("请登录!!!");
            return message;
        }
        else
        {
            if(userInfo.getUserAccount().equals(account)&&userInfo.getUserPassword().equals(pwd)) {
                orderInfoService.saveOrder(cartInfoService, userInfo.getUserId());
                cartInfoService.clear();
                message.setFlag(1);
                message.setMsg("请耐心等待收货!!!");
                return message;
            }
            else
            {
                message.setFlag(2);
                message.setMsg("信息输入有误，提现失败!!!");
                return message;
            }
        }
    }
}

